package com.xtedu.examproject.util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    private static final HikariDataSource dataSource;
    private static String location = "config.properties";
    private static Properties properties;

    static {
        properties = new Properties();
        InputStream in = DBUtil.class.getClassLoader().getResourceAsStream(location);
        try {
            properties.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getValue(String key){
        return properties.getProperty(key);
    }

    static {
        HikariConfig config = new HikariConfig();
        try {
            Class.forName(getValue("db.driver"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        config.setJdbcUrl(getValue("db.url"));
        config.setUsername(getValue("db.username"));
        config.setPassword(getValue("db.password"));

        config.setMaximumPoolSize(10);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);
        dataSource = new HikariDataSource(config);
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
